import { message } from 'antd';
import $ from 'jquery';
import _ from 'lodash';
import 'babel-polyfill';
import fetch from 'isomorphic-fetch';

export const REQUEST_IMAGES = 'REQUEST_IMAGES';
export const RECEIVE_IMAGES = 'RECEIVE_IMAGES';
export const REQUEST_PATIENTS = 'REQUEST_PATIENTS';
export const RECEIVE_PATIENTS = 'RECEIVE_PATIENTS';
export const GET_PATIENTS = 'GET_PATIENTS';
export const GET_PATIENT = 'GET_PATIENT';
export const CREATE_PATIENT = 'CREATE_PATIENT';
export const CHANGE_PAGE = 'CHANGE_PAGE';
export const GET_USER ='GET_USER';
export const CLEAR_USER ='CLEAR_USER';
export const CLEAR_IMAGES ='CLEAR_IMAGES';
export const CLEAR_PATIENTS ='CLEAR_PATIENTS';
export const UPDATE_USER ='UPDATE_USER';
export const FETCH_PORTRAIT ='FETCH_PORTRAIT';
export const RECEIVE_SPECIALIST = 'RECEIVE_SPECIALIST';
export const CLEAR_SPECIALIST = 'CLEAR_SPECIALIST';
export const API_URL = (function(){try{return api_url}catch(e){
     return 'http://192.168.5.250:8082/';
    //return 'http://123.160.246.81:9082/'
        }})(),
        GET_IMAGES ='study',
        DICOMS ='dicoms',
        PATIENT_STUDY ='patientStudy',
        PATIENT ='patient',
        LOGIN = 'signin',
        LOGOUT = 'signout',
        USER = 'user',
        PACSM ='pacs/m',
        PASSWORD = 'password',
        PORTRAIT = 'portrait',
        SEND_MAIL = 'forget_pass',
        MAIL_RESET_PASS = 'reset_pass',
        SEND_SMS = 'sms',
        CHECK_SMS = 'checksms',
        SMS_RESET_PASS = 'sms_pass',
        CHECK_FORM = 'checkrules',
        GET_RULES = 'GET_RULES',
        VERSION = 'version',
        SPECIALIST = 'specialist',
        SPECIAL_UPDATE = 'special/update',
        SPECIAL_REGISTER = 'special/register',
        SPECIAL_EXAMINE = 'special/examine',
        SPECIAL_UPLOAD = 'special/upload',
        SPECIAL_DETAIL = 'special/detail',
        AVAILABLE = 'available',
        ORDER = 'order',
        ORDER_USER = 'order/user',
        ORDER_SPECIALIST = 'order/specialist',
        REPORT = 'report',
        ATTACHMENTS = 'attachments',
        ATTACHMENT = 'attachment',
        UPLOAD = 'upload';
export const FetchURL = {
        GET_IMAGES :'study',
        DICOMS :'dicoms',
        PATIENT_STUDY :'patientStudy',
        PATIENT :'patient',
        LOGIN : 'signin',
        LOGOUT : 'signout',
        USER : 'user',
        PACSM :'pacs/m',
        PASSWORD : 'password',
        PORTRAIT : 'portrait',
        SEND_MAIL : 'forget_pass',
        MAIL_RESET_PASS : 'reset_pass',
        SEND_SMS : 'sms',
        CHECK_SMS : 'checksms',
        SMS_RESET_PASS : 'sms_pass',
        CHECK_FORM : 'checkrules',
        FETCH_DATA : 'basedata',
        SPECIALIST : 'specialist',
        AVAILABLE : 'available',
        CHARGETYPE : 'basedata/chargetype',
        CHECKTYPE : 'basedata/checktype',
        CRITICALITY : 'basedata/criticality',
        GENDER : 'basedata/gender',
        MODALITY : 'basedata/modality',
        NATIONALITY : 'basedata/nationality',
        PATIENTTYPE : 'basedata/patienttype',
        TESTRESULT : 'basedata/testresult',
        TITLE : 'basedata/title',
        IDTYPE : 'basedata/idtype',
        REGION : 'basedata/region',
        ACTION : 'action',
        ROLE : 'role',
        DEPARTMENT : 'basedata/department',
        PRODUCTTYPE : 'basedata/producttype',
        PRODUCT: 'product',
        SPECIALIST_PRODUCT: 'sproduct',//专家产品
        NEWSPRODUCT: 'newsproduct',//新专家产品判断和添加
        SPRODUCT:'sproduct',
        SYSTEMLOG:'systemlog',
        ATTACHMENTS : 'attachments',
        ATTACHMENT : 'attachment',
        UPLOAD : 'upload'

};
/*
* 用户刷新的时候需要重新写入user信息
* */
export function getAccount(){
  if(window.sessionStorage){
      const sessionUser = JSON.parse(window.sessionStorage.getItem('user'));
      if(sessionUser){
        return sessionUser;
      }else{
        return null
      }
  }
}
/**
 * 在actions里面没有router依赖，将就用浏览器对象跳转页面；
 * @param uri => 目标页面名称 string
 */
function jump(uri){
  const _reg = /[\w|\W]+#\//,
    _rootPath = (window.location.href).match(_reg)[0],
    targetPath = _rootPath !== ''?`${_rootPath}${uri}`:`/${uri}`;
  if(targetPath){
    window.location.href = targetPath;
  }
}
function _fetch(
    fetchOpts = {                   //fetch的配置
        apiURI: ``,
        method: 'GET',
        isAuth: false
    },
    query = {},                     //需要加入请求接口的查询字符串，通常是token
    sendData = {},                  //fetch的body，get，delete时没有
    dispatchActions = [],           //请求成功并且业务处理成功时dispatch的其他actions
    success = function(){},         //请求成功并且业务处理成功后的回调
    fail = function(){},            //请求成功并且业务处理失败后的回调
    error = function(){},           //请求失败后的回调
    isShowErrorMsg = true,          //是否显示错误提示
    headers = {'content-type':'application/json; charset=UTF-8'}  //请求头
){
    if(fetchOpts.isAuth){
      const _user = getAccount();
        if(_user){
          query = Object.assign({},query,{accessToken:_user.accessToken})
        }
    }
    const _query = (function(){
        let __q = '',
            _i = 0;
        for(let _q in query){
            if(_i !== 0){
                __q += `&${_q}=${query[_q]}`
            }else{
                __q += `?${_q}=${query[_q]}`;
                _i++
            }
        }
        return __q
    })(),
    _opts = (function(){
        switch (fetchOpts.method){
            case 'GET':
            return {
                method: "GET",
                headers:headers
            };
            case 'DELETE':
            return {
                method: "DELETE",
                headers:headers
            };
            case 'POST':
            return {
                method: "POST",
                headers:headers,
                body:JSON.stringify(sendData)
            };
            case 'PUT':
            return {
                method: "PUT",
                headers:headers,
                body:JSON.stringify(sendData)
            };
            case 'PATCH':
            return {
                method: "patch",
                headers:headers
            };
            default:
            return {
                method: "GET",
                headers:headers
            };
        }
    })();
    return dispatch => {
        return fetch(`${API_URL}${fetchOpts.apiURI}${_query}`,_opts).then(response => {
            return response.json()
        }).then(json => {
            if(json.head.success){
              try{
                if(dispatchActions.length > 0){
                    for(let i= 0;i<dispatchActions.length;i++){
                        dispatch(dispatchActions[i](json))
                    }
                }
                if(Array.isArray(json.content)){
                  const _json = json.content.map(_j=>{
                    if(typeof _j == 'string' || _j.constructor == String)
                      return JSON.parse(_j);
                    else
                      return _j;
                  });
                  json.content = _json
                };
                if(typeof success == 'function')
                    success(json)
              }catch(e){}
            }else{
                if(fetchOpts.isAuth) {
                  const _msg = json.head.msg,
                        cause = /accessToken/.test(_msg);
                    if (cause) {
                        message.error('您的账户已经过期，请重新登录', 3);
                      dispatch(clearImages);
                      dispatch(clearPatients);
                      dispatch(clearSpecialist);
                      dispatch(clearUser);
                      jump('login')
                    } else {
                        if(typeof fail != 'function' && isShowErrorMsg)
                            message.error('操作失败，'+_msg, 2);
                    }
                }
                if(typeof fail == 'function'){
                    fail(json);
                }
            }
        }).catch((e) => {
            if(typeof error != 'function') {
                message.error('网络错误：' + e, 3)
            }
            else{
              error(e)
            }
        })
    }
}

/*
*Get数据时传递的参数对象
* Id=> Id:delete时API接口地址使用
* url=> url：调用接口地址通过FetchURL接口获取url
* isAuth=> isAuth：是否使用accessToken认证
* IsEnabled=> IsEnabled：是否是获取启用状态数据
* Opts=> Opts：url传值数据JSON格式
* SendData=> SendData：post数据
* AfterSuccessDispatch=> AfterSuccessDispatch：成功后调用事件[]数组类型
* Succ=> Succ：成功后调用的回调函数
* Fail=> Fail：失败后调用的回调函数
* Error=>Error：错误后调用的回调函数
* */
export let fetchArgs = {
    Id: '',//datils时API接口地址使用
    URL: '',
    IsAuth: false,
    IsEnabled: false,
    Opts: {},
    SendData: {},
    AfterSuccessDispatch: [],
    Succ: {},
    Fail: {},
    Error: {},
    IsShowErrorMsg: true    //是否显示错误提示
};

/*
 * 获取数据的方法
 * fetchArgs:export let fetchArgs类型参数对象
 * */
export function fetchData(_fetchArgs){
    return _fetch(
        {
            apiURI: `${_fetchArgs.URL}${_fetchArgs.IsEnabled ? '/enabled' : '' || _fetchArgs.Id.length>0 ? '/' + _fetchArgs.Id : ''}`,
            method: 'GET',
            isAuth: _fetchArgs.IsAuth
        },_fetchArgs.Opts,_fetchArgs.SendData,_fetchArgs.AfterSuccessDispatch,_fetchArgs.Succ,_fetchArgs.Fail,_fetchArgs.Error,_fetchArgs.IsShowErrorMsg
    )
}
/**
 * fetchDatum 请求多个基础数据
 * 根据参数datum顺序分发上面的fetchData方法
 * @param datum Array
 * 数组，元素是对象，包括name和enabled两个属性
 * @param success Function
 * 所有数据请求完成后的回调，参数是接收到的所有数据的集合对象，key是数据类型名称
 * @returns Object
 * 最后返回请求到的数据
 * 如果中途有error，直接中断
 * 如果中途有业务处理失败的情况则忽略，继续请求剩余的数据
 */
export function fetchDatum(datum,success){
  return dispatch => {
    if(datum instanceof Array){
      let _data = {},
        count = datum.length,
        failCount = 0;
      datum.forEach(data => {
        dispatch(fetchData({
          URL:`basedata/${[data.name]}`,
          IsAuth: true,
          IsEnabled: data.enabled,
          Succ: function(res){
            _data[data.name] = res.content;
            if(--count < 1){
              if(typeof success == 'function'){
                success(_data);
              }
              return _data
            }
          },
          Fail: function(){
            count++;
            failCount++
          },
          Error: function(e){
            count++;
            failCount++;
            message.error(`网络故障，未能获取 ${data.name} 数据`,2);
            return
          }
        }))
      })
    }else{
      throw new Error('请使用基础数据名组成数组作为fetchDatum方法的参数')
    }
  }
}
/*
 * 新建操作
 * opts => accessToken
 * */
export function createData(_fetchArgs){
    return _fetch(
        {
            apiURI: `${_fetchArgs.URL}${_fetchArgs.Id.length>0 ? '/' + _fetchArgs.Id : ''}`,
            method: 'POST',
            isAuth: _fetchArgs.IsAuth
        },_fetchArgs.Opts,_fetchArgs.SendData,_fetchArgs.AfterSuccessDispatch,_fetchArgs.Succ,_fetchArgs.Fail,_fetchArgs.Error
    )
}

/*
 * 更新操作
 * opts => accessToken
 * */
export function updateData(_fetchArgs){
    return _fetch(
        {
            apiURI: `${_fetchArgs.URL}`,
            method: 'PUT',
            isAuth: _fetchArgs.IsAuth
        },_fetchArgs.Opts,_fetchArgs.SendData,_fetchArgs.AfterSuccessDispatch,_fetchArgs.Succ,_fetchArgs.Fail,_fetchArgs.Error
    )
}
/*
 * 删除操作
 * opts => accessToken
 * */
export function removeData(_fetchArgs){
    return _fetch(
        {
            apiURI: `${_fetchArgs.URL}/${_fetchArgs.Id}`,
            method: 'DELETE',
            isAuth: _fetchArgs.IsAuth
        },_fetchArgs.Opts,_fetchArgs.SendData,_fetchArgs.AfterSuccessDispatch,_fetchArgs.Succ,_fetchArgs.Fail,_fetchArgs.Error
    )
}
/*
* 1、修改资料
 _.post('/special/update', auth.checkToken, user.updateSpecial);
 2、注册
 _.post('/special/register', user.regSpecial);
 3、审核
 _.post('/special/examine', auth.checkToken, user.passSpecial);
 4、上传图像
 _.post('/special/upload', auth.checkToken, user.uploadCard);
 5、根据account_id 获取医生详细详细
 _.get('/special/detail', auth.checkToken, user.getSpecialByAccountId);

 * */
export function special_operate(type,opts,sendData,succ,fail,error){
	let apiURI='',
		method = 'POST',
		isAuth= true;
	switch (type){
		case 'update':
			apiURI = `${SPECIAL_UPDATE}`;
			break;
		case 'register':
			apiURI = `${SPECIAL_REGISTER}`;
			isAuth = false;
			break;
		case 'examine':
			apiURI = `${SPECIAL_EXAMINE}`;
			break;
		case 'upload':
			apiURI = `${SPECIAL_UPLOAD}`;
			break;
		case 'detail':
			apiURI = `${SPECIAL_DETAIL}`;
			method = 'GET';
			break;
	}
	return _fetch(
		{
			apiURI: apiURI,
			method: method,
			isAuth: isAuth
		},opts,sendData,[],succ,fail,error
	)
}
export function check_rules(succ,fail,error){
   return _fetch(
        {
            apiURI: `${CHECK_FORM}`,
            method: 'GET'
        },{/* opts */},{/* request body */},[/*getRules*/],succ,fail,error
    )
}
/*function getRules(json){
  return {
    type: GET_RULES,
    rules: json.content
  }
}*/
export function _fm(opts,succ,fail,error){
   return _fetch(
        {
            apiURI: `${GET_IMAGES}`,
            method: 'GET'
        },opts,{/* request body */},[receiveImages],succ,fail,error
    )
}
export function sendMail(sendData,succ,fail,error){
   return _fetch(
        {
            apiURI: `${SEND_MAIL}`,
            method: 'POST'
        },{},sendData,[/* dispatch some actions after success */],succ,fail,error
    )
}
export function mailResetPass(sendData,succ,fail,error){
   return _fetch(
        {
            apiURI: `${MAIL_RESET_PASS}`,
            method: 'POST'
        },{},sendData,[/* dispatch some actions after success */],succ,fail,error
    )
}
export function sendSms(receiver,succ,fail,error){
    return _fetch(
        {
            apiURI: `${SEND_SMS}/${receiver}`,
            method: 'POST'
        },{/*opts*/},{/*sendData*/},[/* dispatch some actions after success */],succ,fail,error
    )
}
export function checkSms(opts,succ,fail,error){
    return _fetch(
        {
            apiURI: `${CHECK_SMS}`,
            method: 'GET'
        },opts,{/*sendData*/},[/* dispatch some actions after success */],succ,fail,error
    )
}
export function smsResetPass(sendData,succ,fail,error){
    return _fetch(
        {
            apiURI: `${SMS_RESET_PASS}`,
            method: 'PUT'
        },{/* opts */},sendData,[/* dispatch some actions after success */],succ,fail,error
    )
}
/**
 * 产生随机值，用作刷新头像的hash值
 * */
export function randomCode(addtion){
    return (+new Date() + Math.floor(Math.random() * 999999)).toString(36)+((addtion && addtion)|| '');
}
export function fetchPortrait(uid){
    return {
        type:FETCH_PORTRAIT,
        url:`${API_URL}${PORTRAIT}/${uid}?at=${randomCode()}`
    }
}
function requestImages(){
    return {
        type: REQUEST_IMAGES
    }
}
function receiveImages(json){
    return {
        type: RECEIVE_IMAGES,
        images: json.content.list
    }
}
/*
* 修改密码
* opts => accessToken
* */
export function putPW(sendData,succ,fail,error){
    return _fetch(
      {
          apiURL: `${API_URL}`,
          apiURI: `${PASSWORD}`,
          method: 'PUT',
          isAuth:  true
      },{},sendData,[/* dispatch some actions after success */],succ,fail,error
    )
}
/*
 * 获取所有影(检)像(查)，是个列表
 * opts => accessToken
 * */

export function fetchImages(succ,fail,error){
    return _fetch(
      {
          apiURI: `${GET_IMAGES}`,
          method: 'GET',
          isAuth:  true
      },{},{/* sendData */},[receiveImages],succ,fail,error
    )
}/*
 * 获取某个影(检)像(查)
 * */
export function fetchUserImage(id,succ,fail,error){
    return _fetch(
      {
          apiURI: `${GET_IMAGES}/${id}`,
          method: 'GET',
          isAuth: true
      },{},{},[],succ,fail,error)
}
/*
 * 获取某个用户的所有影(检)像(查)。是个列表
 * opts => userid=userid
 * */
export function fetchUserImages(opts,succ,fail,error){
    return _fetch(
      {
          apiURI: `${GET_IMAGES}`,
          method: 'GET',
          isAuth: true
      },opts,{/* sendData */},[receiveImages],succ,fail,error
    )
}
/*
* 新建影像
* */

export function createImage(sendData,succ,fail,error){
    return _fetch(
      {
          apiURI: `${PATIENT_STUDY}`,
          method: 'POST',
          isAuth: true
      },{},sendData,[],succ,fail,error
    )
}/*
* 删除影像
* */
export function deleteImage(studyId){
    return {
        type:'DELETE_IMAGE',
        id:studyId
    }
}
export function removeImage(studyId,succ,fail,error){
    return _fetch(
      {
          apiURI: `${GET_IMAGES}/${studyId}`,
          method: 'DELETE',
          isAuth: true
      },{},{},[],succ,fail,error
    )
}

/*
* 更新影像信息
* 目前仅仅是修改影像状态，管理员审核影像使用的功能
* */

export function upDateImages(image){
    return {
        type:'UPDATE_IMAGES',
        image:image
    }
}
export function updateImage(sendData,succ,fail,error){
    return _fetch(
      {
          apiURI: `${GET_IMAGES}`,
          method: 'PUT',
          isAuth: true
      },{},sendData,[],succ,fail,error
    )
}
/*
* 获取pacs影像的看片地址，由于需要在回调中拼接地址，暂时不使用调用过程中定义回调的形式
* */

export const mPacs = (studyId,succ,fail)=>{
    return () => {
        return fetch(`${API_URL}${PACSM}`,{
            method:'GET',
            headers:{
                'content-type':'application/json; charset=UTF-8'
            }
        }).then(response => {
            return response.json()
        }).then(json => {
            if(json.head.success){
                succ && succ(`${json.content}?studyId=${studyId}`);
                return
            }else{
                fail && fail();
                return '获取移动pacs地址失败'
            }
        }).catch(function(e){
            fail && fail(e);
        })
    }
};



function requestPatients(){
    return {
        type: REQUEST_PATIENTS
    }
}
function receivePatients(json){
    return {
        type: RECEIVE_PATIENTS,
        patients: json.content.list
    }
}
/*
* 查找单个亲(患)友(者)
* pid是uri，患者id
* */
export function fetchPatient(pid,succ,fail,error){
    return _fetch(
      {
          apiURI: `${PATIENT}/${pid}`,
          method: 'GET',
          isAuth: true
      },{},{/*sendData*/},[/* dispatch */],succ,fail,error
    )
}


/*
 * 查找某个用户的所有亲(患)友(者)
 * opts => userid & status
 * */
export function fetchPatients(opts,succ,fail,error){
    return _fetch(
      {
          apiURI: `${PATIENT}`,
          method: 'GET',
          isAuth: true
      },opts,{/*sendData*/},[receivePatients],succ,fail,error
    )
}

/*
 * 创建亲(患)友(者)
 * sendData => 表单数据 & 添加
 * */


export function createPatient(uid,sendData,succ,fail,error){
    const _sendData = Object.assign({},sendData,{status:1,userid:uid});
    return _fetch({
      apiURI: `${PATIENT}`,
      method: 'POST',
      isAuth: true
      },{},_sendData,[/* dispatch */],succ,fail,error
    )}

/*
 * 删除某个(患)友(者)
 * */
export function removePatient(pid,succ,fail,error){
    return _fetch({
      apiURI: `${PATIENT}/${pid}`,
      method: 'DELETE',
      isAuth: true
      },{},{/* sendData */},[/* dispatch */],succ,fail,error
    )}

/*
 * 更新某个(患)友(者)
 * pid => 患者id
 * sendData => 患者信息，表单提交的数据
 * */
export function updatePatient(pid,sendData,succ,fail,error){
    const _sendData = Object.assign({},sendData,{id:pid});
    return _fetch({
      apiURI: `${PATIENT}`,
      method: 'PUT',
      isAuth: true
      },{},_sendData,[/* dispatch */],succ,fail,error
    )}
export function fetchStudyRelatedData(study,succ,fail,error){
  return dispatch =>{
    if(typeof study != 'object'){
      return false
    }else{
      const studyId = study.id,
        pid = study.pid,
        instance = study.study_instance_uid;
      let patient = {},
          mp = '',
          attachments = [],
          complete = 3;
      //正式开始fetch
      function end(n){
        if(--complete < 1){
          let data = {
            patient,
            mp,
            attachments,
            study
          };
          succ(data)
        }
      }
      dispatch(fetchPatient(pid,function(res){
        patient = res.content;
        end('patient')
      },function(){
        patient = null;
        end('patient-null')
      }));
      dispatch(mPacs(instance,function(res){
        mp = res;
        end('mpac')
      },function(){
        mp = '';
        end('mpac-null')
      }));
      dispatch(fetchAttachByEntry({id:studyId,type:'report'},function(res){
        attachments = res.content;
        end('attachments')
      },function(){
        attachments = [];
        end('attachments-null')
      }));
    }
  }
}


/*
 * 注册
 * sendData 提交的表单数据
 * */
export function register(sendData,succ,fail,error){
    return _fetch({
          apiURI: `${USER}`,
          method: 'POST'
      },{/* opts */},sendData,[/* dispatch */],succ,fail,error
    )}
/*
 * 更新用户个人信息
 * sendData => 提交的表单数据
 * */
export function updateUser(sendData,succ,fail,error){
    return _fetch({
        apiURI: `${USER}`,
        method: 'PUT',
        isAuth: true
      },{},sendData,[getUser],succ,fail,error
    )}
export function getUser(json){
    return {
        type: GET_USER,
        user:json.content
    }
}
export function clearUser(){
    return {
        type: CLEAR_USER
    }
}
export function clearImages(){
    return {
        type: CLEAR_IMAGES,
        images:[]
    }
}
export function clearPatients(){
    return {
        type: CLEAR_PATIENTS,
        patients:[]
    }
}

function clearSpecialist(){
  return {
    type: CLEAR_SPECIALIST,
    specialist: []
  }
}

/*
 * 登录，获得用户信息和accessToken
 * */
export function login(sendData,succ,fail,error){
    return _fetch({
          apiURI: `${LOGIN}`,
          method: 'POST'
      },{/*opts*/},sendData,[getUser,clearImages,clearPatients,clearSpecialist],succ,fail,error
    )}

/*
* 表单验证方法
* e => event参数
* context => 调用验证的组件类
* succ => 表单内容无误时的回调
* error => 表单内容有误时的回调
* 通常调用此方法的时机是submit时
* */
export function _validate(e,context,succ,error){
    e && e.preventDefault();
    context.props.form.validateFieldsAndScroll((errors, values) => {
        if (!!errors) {
            message.error('表单填写有错误',1);
            if(typeof error == 'function'){
              error(errors)
            }
            return error;
        }
        if(typeof succ == 'function'){
          succ(values)
        }
    });
}

/*
* 登出
* opts => accessToken
* */
export function logout(succ,fail,error){
  return _fetch({
      apiURI: `${LOGOUT}`,
      method: 'POST',
      isAuth:true
    },{},{},[clearImages,clearPatients,clearSpecialist,clearUser],succ,fail,error
  )
}
export function changePage(uri){
    return {
        type: CHANGE_PAGE,
        uri
    }
}
function _mask(txt){
    setTimeout(function(){
        let _t = txt || '功能暂未开放',
            _wH = $(window).height(),
            _bW = $('#board').size() > 0?$('#board').width():$('#boardSpe').width(),
            _bH = $('#board').size() > 0?$('#board').height():$('#boardSpe').height(),
            _hH = $('#headerWrap').height(),
            _fH = 0,
            height = _bH > (_wH - _hH - _fH)?_bH+'px':(_wH - _hH - _fH)+'px',
            width = _bW+'px',
          left = $('#board').size() > 0? '240px': 0;
        if($('#_mask').size() > 0){
            $('#_mask').css({
                'height':height,
                'width':width,
              'left':left
            }).html('<h2>'+_t+'</h2>')
        }
    },1)

}
export const formItemLayout = {
  labelCol: {
    xs:{span:6},
    sm:{span:6},
    md:{span:6},
    lg:{span:4}
  },
  wrapperCol: {
    xs:{span:18},
    sm:{span:14},
    md:{span:10},
    lg:{span:6}
  },
  noLabel:{
    xs:{span:18,offset:6},
    sm:{span:14,offset:6},
    md:{span:10,offset:6},
    lg:{span:6,offset:4}
  },
  ignore:{
    labelCol: {
      xs:{span:6},
      sm:{span:6},
      md:{span:6},
      lg:{span:4}
    },
    wrapperCol: {
      xs:{span:18},
      sm:{span:18},
      md:{span:18},
      lg:{span:20}
    },
    noLabel:{
      xs:{span:18,offset:6},
      sm:{span:18,offset:6},
      md:{span:18,offset:6},
      lg:{span:20,offset:4}
    }
  }
};
/*
* 参数txt是遮罩中显示的文字内容，如果不定义参数，默认显示‘功能暂未开放’
* */
export function _maskRender(txt){
  _mask(txt);
  $(window).resize(function(){
    _mask(txt)
  });
}

/*
* 医生注册
* sendData => 医生信息表单
* */
export function createSpecialist(sendData,succ,fail,error){
  return _fetch(
    {
      apiURI: `${SPECIALIST}`,
      method: 'POST',
      isAuth: true
    },{},sendData,[],succ,fail,error
  )
}
/*
* 医生更新
* sid => specialist.account_id
* sendData => 医生信息表单
* */
export function updateSpecialist(sid,sendData,succ,fail,error){
  return _fetch(
    {
      apiURI: `${SPECIALIST}/${sid}`,
      method: 'PUT',
      isAuth: true
    },{},sendData,[],succ,fail,error
  )
}
/*
* 获得医生列表
* opts => accessToken
* */

function requestSpecialist(){
  return {
    type: REQUEST_SPECIALIST
  }
}
function receiveSpecialist(json){
  return {
    type: RECEIVE_SPECIALIST,
    specialist: json.content.data
  }
}
export function fetchSpecialists(opts,succ,fail,error){
  return _fetch(
    {
      apiURI: `${SPECIALIST}`,
      method: 'GET'
    },opts,{/* no data need to send */},[receiveSpecialist],succ,fail,error
  )
}

/*
 * 检测用户名、email、手机号是否可用
 * opts => type = data
 * */
function available(opts,succ,fail,error){
  return _fetch(
    {
      apiURI: `${AVAILABLE}`,
      method: 'GET'
    },opts,{ /*sendData*/ },[/* 在成功回调里需要分发deleteImage，参数是studyId，这里的参数只能是res.json */],succ,fail,error
  )
}
export function checkExists(type,rule,value,callback,ignore){
  const typeTxt = type == 'mobile' ? '手机号' : (type == 'username' ? '用户名' : '邮箱');
  return dispatch => {
    if(!value){
      callback();
    }else{
      dispatch(available({type:type,data:value},function(res){
        const _result = res.content.registered;
        if(!!ignore){
          if (_result && value !== ignore) {
            callback([new Error('抱歉，该 '+typeTxt+' 已被占用。')]);
          } else {
            callback();
          }
        }else{
          if (_result) {
            callback([new Error('抱歉，该 '+typeTxt+' 已被占用。')]);
          } else {
            callback();
          }
        }
      }))
    }
  }
}
/*
 * 发布新版本
 * token => accessToken
 * android应用需要上传安装文件，由于不能控制提交时间点，这里不使用antd的upload控件，使用普通的form表单配合jquery的ajax方法实现此功能
 * 这个方法不需要使用dispatch方法分发，直接调用就行了，否则createLogger方法会报错
 * */
export function _public_app(token,sendData,succ,fail,error) {
  let formData = new FormData();
  if(sendData.type == 'android'){
    formData.append("app", sendData.app.file)
  }
  for(let _k in sendData){
    formData.append(_k, sendData[_k]);
  }
  $.ajax({
    url: `${API_URL}${VERSION}?accessToken=${token}`,
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function(res){
      if(res.head.success){
        succ(res)
      }else{
        fail(res)
      }
    },
    error: function(e){
      error(e)
    }
  });
}
/*
 * 获得版本列表
 * type = 'ios' | 'android'
 * opts => accessToken & type
 * */
export function fetchVersionList(opts,succ,fail,error){
  try {
    return _fetch(
      {
        apiURI: `${VERSION}`,
        method: 'GET'
      },opts,{ /*sendData*/ },[/* dispatch*/],succ,fail,error
    )
  }catch(e){}
}
/*
* 获得最新版本
* type = 'ios' | 'android'
* */
export function fetchLatestVersion(type,succ,fail,error){
  try{
  return _fetch(
    {
      apiURI: `${VERSION}/latest?type=${type}`,
      method: 'GET'
    },{/*opts*/},{ /*sendData*/ },[/* dispatch*/],succ,fail,error
  )}catch(e){}
}

/*
 * 获取role(角色)的所有的数据
 * opts => accessToken=accessToken
 * */
export function fetchRoleDetail(id,opts,succ,fail,error){
    return _fetch(
        {
            apiURI: `${FetchURL.ROLE}/${id}`,
            method: 'GET'
        },opts,{},[/* dispatch some roles after success */],succ,fail,error
    )
}

/*
* type:订单类型
*   1- 仅写报告
*   2- 报告和交互
*   null- 全部
* opt: 查询参数，分页，状态，可以不填
* succ: 成功回调
* fail: 业务处理失败回调
* error: 请求错误回调
**/
export function fetchOrderSpecial(type,opts,succ,fail,error){
  let _uri = '';
  if(type == 1){
    _uri = `${ORDER_SPECIALIST}/report`
  }else if(type == 2){
    _uri = `${ORDER_SPECIALIST}/appointment`
  }else{
    _uri = `${ORDER_SPECIALIST}`
  }
  return _fetch(
    {
      apiURI: `${_uri}`,
      method: 'GET',
      isAuth: true
    },opts,{},[],succ,fail,error
  )
}
/**
 * 根据订单号获取订单相关报告
 * @param order:订单号
 * @param succ
 * @param fail
 * @param error
 */
export function fetchReport(order,succ,fail,error){
  return _fetch(
    {
      apiURI: `${REPORT}/${order}`,
      method: 'GET',
      isAuth: true
    },{},{},[],succ,fail,error
  )
}
/**
 * 创建报告
 * @param sendData body-json
 * @param succ
 * @param fail
 * @param error
 */
export function createReport(sendData,succ,fail,error){
  return _fetch(
    {
      apiURI: `${REPORT}`,
      method: 'POST',
      isAuth: true
    },{},sendData,[],succ,fail,error
  )
}
/**
 * 编辑报告
 * @param sendData
 * @param succ
 * @param fail
 * @param error
 */
export function editReport(sendData,succ,fail,error){
  return _fetch(
    {
      apiURI: `${REPORT}`,
      method: 'PUT',
      isAuth: true
    },{},sendData,[],succ,fail,error
  )
}
/**
 *
 * @param sendData
 * @param succ
 * @param fail
 * @param error
 */
export function getTheUser(userId,succ,fail,error){
  return _fetch(
    {
      apiURI: `user/${userId}`,
      method: 'GET',
      isAuth: true
    },{},{},[],succ,fail,error
  )
}
/**
 * 获取订单相关数据
 * @param order 订单实体，对象
 * @param succ  成功回调
 * @returns {Function}
 * @return data
 *  study       影像
 *  patient     患者
 *  mp          阅片地址
 *  order       订单
 *  user        下单用户
 *  report      报告
 *  attachments 附件
 */
export function fetchOrderRelatedData(order,succ){
  return dispatch =>{
    if(typeof order != 'object'){
      return false
    }else{
      const studyId = order.study_id,
        orderId = order.id,
        userId = order.user_id;
      let pid = '',
        study = {},
        patient = {},
        report = {},
        instance = '',
        user = {},
        mp = '',
        attachments = [],
        complete = 5;//由于订单信息不需要获取，所以仅获取5项即可
      dispatch(fetchUserImage(studyId,function(res){
        pid = res.content.pid;
        study = res.content;
        instance = res.content.study_instance_uid;
        //正式开始fetch
        function end(n){
          if(--complete < 1){
            let data = {
              study,
              patient,
              report,
              user,
              mp,
              attachments
            };
            succ(data)
          }
        }
        dispatch(fetchPatient(pid,function(res){
          patient = res.content;
          end('patient')
        },function(){
          patient = null;
          end('patient')
        }));
        dispatch(fetchReport(orderId,function(res){
          const _rp = res.content;
          if(_rp.hasOwnProperty('id')){
            report = _rp;
          }else{
            report = null;
          };
          end('report')
        },function(){
          report = null;
          end('report')
        }));
        dispatch(getTheUser(userId,function(res){
          user = res.content.user;
          end('user')
        },function(){
          user = null;
          end('user')
        }));
        dispatch(mPacs(instance,function(res){
          mp = res;
          end('mpac')
        },function(){
          mp = null;
          end('mpac')
        }));
        dispatch(fetchAttachByEntry({id:studyId,type:'report'},function(res){
          attachments = res.content;
          end('attachment')
        },function(){
          attachments = '暂无附件';
          end('attachment')
        }));
      },function(res){
        message.warning(`获取订单相关影像数据失败：${res.head.msg}`,2)
        end()
      },function(e){
        message.error(`数据请求失败，请检查您的网络是否畅通:${e}`,2)
        end()
      }))
    }
  }
}
/**
 *
 * @param orderId
 * @param type 操作类型 pay,cancel,process,completion,deletion
 * @param succ
 * @param fail
 * @param error
 */
export function orderOperator(orderId,type,succ,fail,error){
  return _fetch(
    {
      apiURI: `${ORDER}/${orderId}/${type}`,
      method: 'PUT',
      isAuth: true
    },{},{},[],succ,fail,error
  )
}
/**
 *
 * @param orderId 订单id
 * @param succ
 * @param fail
 * @param error
 */
export function openWeiyi(orderId,succ,fail,error){
  return _fetch(
    {
      apiURI: `meeting/url/${orderId}/1`,
      method: 'GET',
      isAuth: true
    },{},{},[],succ,fail,error
  )
}
/**
 * 根据实体ID查询该实体关联的所有附件
 * @param param
 *  实体对象，是个对象奥类型的参数，其中必须定义entry.id
 *  如果同时定义了entry.type，则查询该实体关联的特定type的附件
 * @param succ
 *  查询成功回调
 * @param fail
 *  查询失败回调
 * @param error
 * 请求错误回调
 */
export function fetchAttachByEntry(entry,succ,fail,error){
  let _uri = '';
  if(entry.id && entry.type){
    _uri = `${ATTACHMENTS}/${entry.id}/${entry.type}`
  }else if(entry.id){
    _uri = `${ATTACHMENTS}/${entry.id}`
  }else{
    return {}
  }
  return _fetch(
    {
      apiURI: _uri,
      method: 'GET',
      isAuth: true
    },{},{},[],succ,fail,error
  )
}
/**
 * 操作单个附件
 * @param id
 *  附件id string
 * @param opt
 *  操作方式 默认是 get，0 => delete
 * @param succ
 * @param fail
 * @param error
 */
export function fetchAttachById(id,opt,succ,fail,error){
  let _method = 'GET';
  if(opt == 0){
    _method = 'DELETE'
  }
  return _fetch(
    {
      apiURI: `${ATTACHMENT}/${id}`,
      method: _method,
      isAuth: true
    },{},{},[],succ,fail,error
  )
}
export function uploadChangeHandle(cate,info,context){
  const status =info.file.status;
  switch (status) {
    case 'uploading':
      break;
    case 'removed':
      const _file = info.file;
      let aid = ''
      if(_file.response){
        aid = _file.response.content;
        let _fileList = context.state.fileList,
          _cate = _fileList[cate];
          _.remove(_cate,o=>{
            return o == aid
          })
        _fileList[cate] = _cate;
        context.setState({
          attachment:_fileList,
        })
      }else{
        aid = _file.id
      }
      context.props.dispatch(fetchAttachById(aid,0));
      break;
    case 'done':
      let fileList = context.state.fileList;
      if(!fileList[cate]){
        fileList[cate] = []
      }
      fileList[cate].push(info.file.response.content);
      context.setState({
        attachment:fileList,
        submitDisabled: false
      });
      break;
    case 'error':
      context.setState({
        submitDisabled: false
      });
      break;
    default:
      context.setState({
        submitDisabled: false
      });
  }
}
export function deleteDicom(batchId,succ,fail,error){
  return _fetch(
    {
      apiURI: `${DICOMS}/${batchId}`,
      method: 'DELETE',
      isAuth: true
    },{},{},[],succ,fail,error
  )
}
export function portraitSet(info,context,succ){
  let status = info.file.status;
  switch (status) {
    case 'uploading':
      break;
    case 'done':
      let fileList = context.state.fileList,
        aid = info.file.response.content,
        portrait = {};
      if(fileList['portrait'] && fileList['portrait'].length > 0){
        const curPort = fileList['portrait'][0];
        context.props.dispatch(fetchAttachById(curPort,0));
        fileList['portrait'] = [];
      }else{
        const _po = context.state.portrait;
        if(_po){
          context.props.dispatch(fetchAttachById(_po.id,0));
        }
        fileList['portrait'] = [];
      }
      fileList['portrait'].push(aid);
      portrait = {
        id: aid,
        url:`${API_URL}attachment/${aid}?accessToken=${context.state.user.accessToken}`
      }
      context.setState({
        attachment:fileList,
        portrait:portrait,
        submitDisabled: false
      },function(){
        if(typeof succ == 'function'){succ(portrait)}
      });
      //清除上传列表
      info.fileList = null
      break;
    case 'error':
      context.setState({
        submitDisabled: false
      });
      break;
    default:
      context.setState({
        submitDisabled: false
      });
  }
}